package ru.efko.dims.util;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.widget.Toast;

public final class ConnectionMonitor {

	private static Future<Boolean> IS_CONNECTED = null;

	private static ScheduledExecutorService CONNECTION_MONITOR = Executors
			.newSingleThreadScheduledExecutor();

	public static Future<Boolean> getIsConnected() {
		return IS_CONNECTED;
	}

	public static void setIsConnected(Future<Boolean> isConnected) {
		IS_CONNECTED = isConnected;
	}

	public static void connectionMonitorStart(final Context applicationContext) {
		final Runnable monitor = new Runnable() {

			@Override
			public void run() {
				try {
					if (IS_CONNECTED != null && !IS_CONNECTED.get()) {
						unableToExecuteTask(applicationContext);
					}
				} catch (InterruptedException e) {
					unableToExecuteTask(applicationContext);
				} catch (ExecutionException e) {
					unableToExecuteTask(applicationContext);
				}

			}
		};
		CONNECTION_MONITOR.scheduleAtFixedRate(monitor, 10, 10,
				TimeUnit.SECONDS);

	}

	private static void unableToExecuteTask(Context applicationContext) {
		CharSequence text = "Unable to get connection!";
		int duration = Toast.LENGTH_SHORT;

		Toast toast = Toast.makeText(applicationContext, text, duration);
		toast.show();
	}

	public static void stopConnectionMonitor() {
		if (!CONNECTION_MONITOR.isShutdown()) {
			IS_CONNECTED.cancel(false);
			CONNECTION_MONITOR.shutdown();
			try {
				if (!CONNECTION_MONITOR.awaitTermination(3, TimeUnit.SECONDS)) {
					CONNECTION_MONITOR.shutdownNow();
				}
			} catch (InterruptedException ie) {
				CONNECTION_MONITOR.shutdownNow();
				Thread.currentThread().interrupt();
			}
		}
	}

}
